<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use think\exception\ValidateException;
use think\facade\View;
use think\response\Json;
use WeMini\Crypt;

class Login extends Base
{

    /**
     * @return Json
     * 原点 2022年2月16日14:16:31 小程序授权登录
     */
    public function miniAppletLogin(): Json
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'MiniAppletLogin');
            $result = (new Crypt(config('pay')['wechat']))->session($param['code']);

            $result['nickname'] = $param['nickname'];
            $result['photo'] = $param['photo'];
            return json(User::_miniAppletSave($result));
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
    public function check(): Json
    {
        try {
            $param = $this->request->post('', '', $this->filter);

            //print_r( $param);die;
            $this->validate($param, 'Login');
            $user = User::where('code|mobile', $param['mobile'])->where('is_del', 0)->find();
            if (empty($user)) return json(['code' => -1, 'msg' => '账号不存在']);

            if ($user['password'] != md5($param['password'])) {
                return json(['code' => -1, 'msg' => '密码错误']);
            }
            if ($user['is_lock'] == 1) {
                return json(['code' => -1, 'msg' => '账号已冻结']);
            }
            $time = time();
            $token = md5(json_encode($user) . $time . $this->request->ip());
            $user->token = $token;
            $user->last_time = $time;
            $user->last_ip = $this->request->ip();
            $user->save();
            return json(['code' => 1, 'msg' => '登录成功', 'token' => $token]);
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
}
